package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-06
 */
@Service

public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //检验老人是否已入住(通过身份证号)

        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();

        LambdaQueryWrapper<Elder> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(checkInElderDto.getIdCardNo() != null, Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        queryWrapper.eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(queryWrapper);

        //老人已入住 throw
        if(ObjectUtils.isNotEmpty(elder)){
            throw new BaseException("老人已入住");
        }


        //老人未入住
        //更新床位已入住
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        Bed bed = bedMapper.selectBedById(checkInConfigDto.getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //新增或更新老人
        Elder elder1 = insertOrUpdate(checkInElderDto, bed);
        //新增签约办理
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();

        //elderId contractNumber elderName startDate endDate status sortOrder
        insertContract(checkInContractDto, checkInConfigDto, elder1);

        //新增入住信息

        //elderName elderId startDate endDate nursingLevelName bedNumber status sortOrder
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        CheckIn checkIn = insertCheckInn(checkInElderDto, checkInConfigDto, elder1, bed, elderFamilyDtoList);

        //新增入住配置

        //checkInId
        insertCheckInConfig(checkInConfigDto, checkIn);




    }

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        //查询入住信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckIn checkInById = getById(id);
        CheckInConfig checkInConfigByCheckInId = checkInConfigMapper.selectCheckInConfigByCheckInId(checkInById.getId());

        if(checkInConfigByCheckInId != null){

            BeanUtils.copyProperties(checkInConfigByCheckInId, checkInConfigVo);
        }
        checkInConfigVo.setStartDate(checkInById.getStartDate());
        checkInConfigVo.setEndDate(checkInById.getEndDate());

        checkInConfigVo.setBedNumber(checkInById.getBedNumber());

        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //查旬老人信息

        Long elderId = checkInById.getElderId();
        Elder elder = elderMapper.selectElderByCheckInsElderId(elderId);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        Integer birthday = Integer.parseInt(elder.getIdCardNo().substring(6, 10));

        Integer age = LocalDate.now().getYear() - birthday;
        checkInElderVo.setAge(age);

        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        Long elderId1 = elder.getId();
        //查询合同
        Contract contract = contractMapper.selectContractByElderId(elderId1);
        checkInDetailVo.setContract(contract);
        //查询入住配置
        //转换家属列表
        String remark = checkInById.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);
        //整合数据返回

        return checkInDetailVo;
    }


    private void insertCheckInConfig(CheckInConfigDto checkInConfigDto, CheckIn checkIn) {

        CheckInConfig checkInConfig = new CheckInConfig();
        checkInConfig.setCheckInId(checkIn.getId());
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckInn(CheckInElderDto checkInElderDto, CheckInConfigDto checkInConfigDto, Elder elder1, Bed bed, List<ElderFamilyDto> elderFamilyDtoList) {
        //elderName elderId startDate endDate nursingLevelName bedNumber status sortOrder
        CheckIn checkIn = new CheckIn();

        BeanUtils.copyProperties(checkInElderDto, checkIn);
        checkIn.setElderId(elder1.getId());
        checkIn.setElderName(elder1.getName());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());

        checkIn.setStatus(0);

        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));

        checkInMapper.insert(checkIn);
        return checkIn;
    }


    private void insertContract(CheckInContractDto checkInContractDto, CheckInConfigDto checkInConfigDto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto, contract);

        //elderId contractNumber elderName startDate endDate status sortOrder
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        Integer status = checkInConfigDto.getStartDate().isBefore(LocalDateTime.now()) ? 1: 0;
        contract.setStatus(status);
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());

        String number = "AA" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(number);

        contractMapper.insert(contract);
    }

    private Elder insertOrUpdate(CheckInElderDto checkInElderDto, Bed bed) {
        //status bedId bedNumber
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);


        //查旬老人信息，身份证号码， 状态不为1
        LambdaQueryWrapper<Elder> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(checkInElderDto.getIdCardNo() != null, Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        queryWrapper.eq(Elder::getStatus, 1);
        Elder selectOne = elderMapper.selectOne(queryWrapper);

        //如果找到了 更新 没找到 增加
        if(ObjectUtils.isEmpty(selectOne)){
            elderMapper.insert(elder);

        } else {
            elderMapper.updateById(elder);
        }

        return elder;

    }

}

